<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>19-鼠标绘制多线</title>
		<style type="text/css">
			body {
				margin: 0;
				overflow: hidden;
			}
			#canvas {
				background-color: antiquewhite;
			}
		</style>
	</head>
	<body>
		<canvas id="canvas"></canvas>
		<!-- glsl es 语言 -->
		<!-- 顶点着色器 -->
		<script id="vertexShader" type="x-shader/x-vertex">
			attribute vec4 a_Position;
			void main() {
				// 点位 x y z 一个顶点到相机的距离
				gl_Position = a_Position;
				// 尺寸
				gl_PointSize = 20.0;
			}
		</script>
		<!-- 片元着色器 -->
		<script id="fragmentShader" type="x-shader/x-fragment">
			precision mediump float;
			uniform vec4 u_FragColor;
			void main() {
				float dist = distance(gl_PointCoord, vec2(0.5, 0.5));
				if (dist < 0.5) {
					gl_FragColor = vec4(1, 1, 0, 1);
				} else {
					discard;
				}
			}
		</script>
		<script type="module">
			import { initShaders, getMousePosInWebgl } from "./js/utils.js"
			import Poly from "./js/poly.js";
			import Sky from "./js/sky.js";
			const canvas = document.querySelector("#canvas");
			canvas.width = window.innerWidth;
			canvas.height = window.innerHeight;
			
			const vsSource = document.querySelector("#vertexShader").innerText;
			const fsSource = document.querySelector("#fragmentShader").innerText;
			
			const gl = canvas.getContext("webgl");
			gl.clearColor(0, 0, 0, 1);
			gl.clear(gl.COLOR_BUFFER_BIT);
			
			// 初始化着色器
			// 功能：解析着色器文本，整合到程序对象里,关联webgl上下文对象，实现两种语言的
			initShaders(gl, vsSource, fsSource);
			
			const sky = new Sky(gl);
			let poly = null;
			canvas.oncontextmenu = function() {
				return false;
			};
			canvas.addEventListener("mousedown", (event) => {
				// 鼠标右键删除
				if (event.button === 2) {
					popVertice();
					return render();
				} 
				const { x, y } = getMousePosInWebgl(event, canvas);
				// 如果存在线就填写一个点
				if (poly) {
					poly.addVertice(x, y);
					return render();
				}
				// 不存在创建一个
				crtPoly(x, y);
				render();
			});
			
			canvas.addEventListener("mousemove", (event) => {
				if (poly) {
					const { x, y } = getMousePosInWebgl(event, canvas);
					poly.setVertice(poly.count - 1, x, y);
					render();
				}
			});
			
			function crtPoly(x, y) {
				poly = new Poly({
					vertices: [ x, y, x, y ],
					types: ['POINTS', 'LINE_STRIP']
				});
				sky.add(poly);
			}
			
			function popVertice() {
				poly.popVertice();
				poly = null;
			}
			
			function render() {
				gl.clear(gl.COLOR_BUFFER_BIT);
				sky.draw();
			}
		</script>
	</body>
</html>
